<template>
	<view class="home">
		<z-paging ref="paging" refresher-only :use-refresher-status-bar-placeholder="true" @onRefresh="onRefresh">
			<!-- 页面内容 -->

			<u-navbar @leftClick="leftClick" @rightClick="rightClick" bgColor="#f2f1f6" placeholder
				:safeAreaInsetTop="true" title="选择闸门" :fixed="true" rightIcon="plus">
			</u-navbar>
			<view class="">
				<u-subsection mode="button" bgColor="#f2f1f6" activeColor="#35a39f" :list="subsectionList" :current="curNow" @change="sectionChange"></u-subsection>
			</view>
			<!-- 分类 -->
			<u-tabs :list="tabsList" keyName="text" @click="renttabsFn"></u-tabs>
			<!-- 提示 -->
			<view class="" v-if="gatelist.length == 0">
				<u-empty mode="list">
				</u-empty>
			</view>
			<!-- 列表 -->
			<distance-sorter :locations="gatelist" :current-location="currentPos">
				<template v-slot:item="{ item, index }">
					<!-- 完全自定义的内容 -->
					<view class="swipe-action">
						<u-swipe-action>
							<u-swipe-action-item :options="options" @click="(e) => handleActionClick(e, item, index)">
								<view class="topitem" @click="urlCezhan(item)">
									<view class="topname">
										<view>{{item.name}}</view>
										<view class="text">编号：{{item.gateNum}}</view>
									</view>
									<view class=""
										style="display: flex;align-items: center;justify-content: space-between;">
										<view class="topdik">
											<view class="zuidkk">
												<view class="xishutt">最大开度：</view>
												<view class="xishu-tt">
													{{item.upperLimit}}
												</view>
												<view class="">
													cm
												</view>
											</view>
											<view class="zuidkk">
												<view class="xishutt">当前开度：</view>
												<view class="xishu-tt">
													{{item.initialPosition}}
												</view>
												<view class="">
													cm
												</view>
											</view>

											<view class="zuidkk">
												<view class="xishutt">直线距离：</view>
												<view class="xishu-tt">
													{{formatDistance(item.distance)}}
												</view>
												<view class="map" @click.stop="handleBbb(item)">
													地图
												</view>
												<!-- <view class="butt_off"
													:class="item.initialPosition==0? 'butt_off':'butt_on'">
													{{ item.initialPosition == 0 ? '未开启' : '已开启' }}
												</view> -->
											</view>
											<view class="zuiflx">
												<view class="zuiite" v-if="findById(qudaoList,item.channel).text">
													<!-- <view class="xishutt">渠道：</view> -->
													<view class="" style="color: #ffaa00;">
														{{findById(qudaoList,item.channel).text}}
													</view>
												</view>
												<view class="zuiite" v-if="findById(bumenList,item.department).text">
													<!-- <view class="xishutt">部门：</view> -->
													<view class="" style="color: #8749de;">
														{{findById(bumenList,item.department).text}}
													</view>
												</view>
											</view>
										</view>
										<view class="zhuzh">
											<!-- 使用组件，直接传入rpx高度值 -->
											<sluice-gate
												:gate-height="visualizationHeight(item.upperLimit,item.initialPosition)*1"
												:set-height="item.initialPosition*1" gate-color="#4392f8"
												text-bg-color="rgba(0,0,0,0.7)" text-color="#fff" />
										</view>
									</view>

								</view>
							</u-swipe-action-item>
						</u-swipe-action>
					</view>
				</template>
			</distance-sorter>
			<!-- 			</uni-swipe-action-item>
		</uni-swipe-action> -->
			<!-- 切换 -->
			<u-modal showCancelButton :show="showmodal" :title="titlemodal" @confirm="confirmFn"
				@cancel="cancelFn"></u-modal>
		</z-paging>
	</view>
</template>

<script>
	import SluiceGate from '@/components/SluiceGate.vue';
	import formItem from '../../uni_modules/uview-ui/libs/config/props/formItem'
	import DistanceSorter from '@/components/DistanceSorter.vue'
	export default {
		components: {
			DistanceSorter,
			SluiceGate
		},
		data() {
			return {
				subsectionList: [
					'全部', '渠道', '部门'
				],
				curNow: 0,
				gateHeight: 200, // 直接使用rpx单位的高度值
				setHeight: 0.235, // 直接使用rpx单位的高度值
				options: [{
					text: '修改',
					icon: 'edit-pen-fill',
					style: {
						color: '#212529',
						backgroundColor: '#ffc107',

					}
				}, {
					text: '删除',
					icon: 'trash-fill',
					style: {
						color: '#ffffff',
						backgroundColor: '#dc3545'
					}
				}],
				titlemodal: '是否删除',
				showmodal: false,
				gatelist: [],
				ty: '',
				toolName: '',
				currentMeterType: null,
				gateID: '', //删除ID
				currentPos: {
					latitude: 0,
					longitude: 0
				},
				qudaoList: [],
				bumenList: [],
				qudaobumenARR:[],
				tabsList:[],
				departmentalChannel:''
			}
		},
		onShow() {
			// 渠道
			this.qudaoList = this.vuex_qudao
			// 部门
			this.bumenList = this.vuex_bumen
			// 闸门
			this.gatelist = this.vuex_initPosiVX
			// 所有
			this.qudaobumenARR = this.vuex_initPosiVX
			// 获取当前位置
			this.obtainTheCurrentPosition()
		},
		onLoad(option) {
			this.ty = option.ty
			this.toolName = option.toolName
			this.currentMeterType = option.currentMeterType
			uni.startPullDownRefresh();
		},
		methods: {
			// 地图
			 handleBbb(i) {
				 //在起始页面跳转到test.vue页面并传递参数
				 uni.navigateTo({
				 	url: '/pages/waterSupplyManagement/maps/mapItem?lng='+i.longitude + '&lat=' + i.latitude + '&nickName=' + i.name
				 });

			    console.log("点击了地图",i);
			  },
			// 分类
			sectionChange(index) {
				this.curNow = index;
				let arr = []
				// 切换
				this.tabsList = []
				if(index == 0){
					this.gatelist = this.qudaobumenARR
				}
				if(index == 1){
					arr = this.filterEmptyFieldObjects(this.qudaobumenARR,'channel')
					this.gatelist = arr
					// 切换
					this.tabsList = this.qudaoList
					this.departmentalChannel = 'channel'
				}
				if(index == 2){
					arr = this.filterEmptyFieldObjects(this.qudaobumenARR,'department')
					this.gatelist = arr
					// 切换
					this.tabsList = this.bumenList
					this.departmentalChannel = 'department'
				}
			},
			// 渠道部门分类
			renttabsFn(i){
				let arr = []
				if(this.departmentalChannel == 'channel'){
					arr = this.findObjectsByField(this.qudaobumenARR,'channel',i.value)
				}
				if(this.departmentalChannel == 'department'){
					arr = this.findObjectsByField(this.qudaobumenARR,'department',i.value)
				}
				this.gatelist = arr
				console.log('i',arr);
			},
			// 可视化高度
			visualizationHeight(max, dq) {
				let nub = dq / max * 200
				return nub
			},
			// 下拉刷新被触发
			onRefresh() {
				// 获取当前位置
				this.obtainTheCurrentPosition()
				// 告知z-paging下拉刷新结束，这样才可以开始下一次的下拉刷新
				setTimeout(() => {
					// 1.5秒之后停止刷新动画
					this.$refs.paging.complete();
				}, 1500)
			},
			obtainTheCurrentPosition() {
				uni.getLocation({
					type: 'wgs84',
					success: (res) => {
						this.currentPos.longitude = res.longitude
						this.currentPos.latitude = res.latitude
					}
				});
			},
			// 格式化距离显示
			formatDistance(distance) {
				if (distance >= 1000) {
					return (distance / 1000).toFixed(2) + '公里'
				}
				return distance + '米'
			},
			// 获取状态颜色
			getStatusColor(status) {
				let data = status.initialPosition * 1
				let nub = 0
				// 判断 data 所在的区间
				if (data >= 0 && data < 30) {
					nub = 3
				} else if (data >= 30 && data < 50) {
					nub = 2
				} else if (data >= 50 && data < 70) {
					nub = 1
				} else if (data >= 70) {
					nub = 0
				}
				const colors = {
					0: '#ff5c26', // 关闭-红色
					1: '#ffbb1a', // 开启中-橙色
					2: '#4CD964', // 已开启-绿色
					3: '#569ce7' // 故障-灰色
				}
				return colors[nub] || '#8E8E93'
			},
			// 按钮组
			handleActionClick(event, item, index) {
				if (this.options[event.index].text == '修改') {
					uni.$u.vuex('vuex_initPosiItem', item)
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/waterSupplyManagement/gateAdd?id=' + item.id + '&createAType=' +
								'修改'
						})
					}, 50)
				}
				if (this.options[event.index].text == '删除') {
					this.cezhancliFn(item.id)
				}
				// 其他逻辑...
			},
			// 删除
			cezhancliFn(id) {
				this.gateID = id
				this.showmodal = true
			},
			confirmFn() {
				this.cezhanitem()
				this.showmodal = false
				console.log('确定');
			},
			cancelFn() {
				this.showmodal = false
				console.log('取消');
			},
			// 删除ID
			cezhanitem() {
				let it = this.gateID
				let arr = this.vuex_initPosiVX
				let index = arr.findIndex(item => item.id == it);
				if (index !== -1) {
					arr.splice(index, 1);
				}
				this.gatelist = arr
				uni.$u.vuex('vuex_initPosiVX', arr)
			},
			urlCezhan(item) {
				uni.$u.vuex('vuex_initPosiItem', item)
				setTimeout(() => {
					if (this.toolName == '手动') {
						uni.navigateTo({
							url: '/pages/waterSupplyManagement/hoistManual'
						});
					}
					if (this.toolName == '计算') {
						uni.navigateTo({
							url: '/pages/waterSupplyManagement/hoistCalculation'
						});
					}
					if (this.toolName == '定距') {
						uni.navigateTo({
							url: '/pages/waterSupplyManagement/hoistDistance'
						});
					}
					if (this.toolName == '定位') {
						uni.navigateTo({
							url: '/pages/waterSupplyManagement/hoistPosition'
						});
					}
				}, 50)
			},
			// 返回
			leftClick() {
				uni.navigateBack({
					delta: 1
				});
			},
			// 添加
			rightClick() {
				let id = new Date().getTime()
				uni.navigateTo({
					url: '/pages/waterSupplyManagement/gateAdd?id=' + id + '&createAType=' + '创建'
				});
			},
			// 查找数组中指定ID对象的函数
			findById(arr, id) {
				// 检查参数有效性
				if (!Array.isArray(arr)) {
					console.error('第一个参数必须是数组');
					return '';
				}

				// 使用find方法查找匹配项
				const foundItem = arr.find(item => {
					// 确保item存在且有id属性
					return item && item.value != null && item.value.toString() == id.toString();
				});
				// 如果找到则返回对象，否则返回空字符串
				return foundItem !== undefined ? foundItem : '';
			},
			// 筛选数组中指定字段为空的对象
			filterEmptyFieldObjects(array, field) {
			 let ARR = [];
			   
			   // 检查输入参数是否有效
			   if (!Array.isArray(array)) {
			     console.error('第一个参数必须是一个数组');
			     return ARR;
			   }
			   
			   if (typeof field !== 'string' || field.trim() === '') {
			     console.error('第二个参数必须是一个非空字符串');
			     return ARR;
			   }
			   
			   // 遍历数组，筛选出指定字段不为空的对象
			   ARR = array.filter(item => {
			     // 检查对象是否存在
			     if (typeof item !== 'object' || item === null) {
			       return false;
			     }
			     
			     // 检查字段值是否不为空（排除undefined、null、空字符串）
			     const value = item[field];
			     return value !== undefined && value !== null && value !== '';
			   });
			   
			   return ARR;
			},
			// 查找数组中所有 value 为指定值的对象
			findObjectsByField(arr, field, value) {
			  if (!Array.isArray(arr)) {
			    console.error('第一个参数必须是数组');
			    return [];
			  }
			
			  // 使用 filter 返回所有匹配的对象（新数组）
			  return arr.filter(item => item && item[field] === value);
			}
		}
	}
</script>
<style scoped lang="scss">
	.swipe-action {
		margin: 10rpx;
	}

	.topitem {
		padding: 20rpx;
		border-radius: 20rpx;
		// background-color: rgba(#ffffff, 1);
		// border: 1rpx solid rgba(#cce5ff, 5);

		.topname {
			font-size: 38rpx;
			font-weight: bold;
			color: #35a39f;
			display: flex;
			align-items: center;
			justify-content: space-between;
			border-bottom: 1rpx solid rgba(#4ECDC4, 1);

			.text {
				padding: 5rpx 20rpx;
				border-radius: 50rpx;
				font-size: 30rpx;
				font-weight: 500;
			}
		}

		.topdik {
			font-size: 30rpx;
			padding: 0 10rpx;
			.zuiflx {
				display: flex;
				justify-content: space-around;
				align-items: center;
			}

			.zuidkk {
				width: 500rpx;
				border-bottom: 1rpx solid rgba(#f5f5f5, 1);
				display: flex;
				align-items: center;
				justify-content: space-between;

				.xishu-tt {
					font-size: 40rpx;
					color: #000000;
				}
				.map {
					padding: 0 10rpx;
					border-radius: 5rpx;
					color: #ffffff;
					background-color: #117d8d;
					&:active {
						background-color: #17a2b8;
					}
				}

				.butt_off {
					width: 130rpx;
					text-align: center;
					color: #ffffff;
					border-radius: 50rpx;
					background-color: #9f9f9f;
				}

				.butt_on {
					width: 130rpx;
					text-align: center;
					color: #ffffff;
					border-radius: 50rpx;
					background-color: #00aa00;
				}
			}
			.zuiflx {
				width: 500rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
				.zuiite {
					width: 50%;
				}
			}
		}
		.zhuzh {
			margin-top: 20rpx;
		}
	}

	.conttit {
		margin: 20rpx;
		text-align: center;
		color: #ffffff;
		padding: 10rpx;
		font-size: 30rpx;
		border-radius: 30rpx;
		background: rgba(#17a2b8, 1);
		transition: all 0.2s ease;
	}

	.conttit:active {
		transform: scale(0.9);
		background: rgba(#117d8d, 1);
	}
</style>
<style>
	page {
		background-color: #f2f1f6;
	}
</style>